<?php
declare (strict_types = 1);

namespace app\api\subscribe;

use think\Event;
use think\facade\Db;
use think\facade\Queue;

class User
{
    /**
     * 用户注册事件
     * */
    public function onUserRegister($user)
    {
        list($user_id,$parent_id) = $user;

        $level_path = $this->getUserLevelPath($parent_id);

        // $this->generateLevelData($level_path,$user_id);
        $this->inviteTask($parent_id);
    }


    public function subscribe(Event $event)
    {
        $event->listen('UserRegister',[$this,'onUserRegister']);
    }

    public function inviteTask($parent_id)
    {
        $tasks = $this->getUserInviteTask($parent_id);
        if (!$tasks->isEmpty()){
            foreach ($tasks as $v){
                $finish_join_num = $v['finish_join_num']+1;
                if ($v['join_num'] == $finish_join_num){
                    $this->changeUserTask($v['id'],['finish_join_num' => $finish_join_num,'task_status' => 2]);
                    if ($v['task_type']==1){
                        Queue::push('app\store\job\Account@integral',[
                            'user_id' => $parent_id,
                            'desc' => '邀请好友',
                            'change_type'=>1,
                            'integral' => $v['give_integral']
                        ]);
                    }
                    if ($v['task_type']==6){
                        $this->changeOrderStatus($v['order_id']);
                    }

                    if (!empty($v['give_coupon'])){
                        foreach ($v['give_coupon'] as $v1){
                            Queue::push('app\store\job\Coupon',[
                                'user_id' => $parent_id,
                                'coupon_id' => $v1['coupon_id'],
                                'num' => $v1['num'],
                            ],'userCoupon');
                        }
                    }

                }else {
                    $this->changeUserTask($v['id'],['finish_join_num' => $finish_join_num]);
                }
            }

        }

    }

    /**
     * 修改订单状态
     * */
    public function changeOrderStatus($order_id)
    {
       $result = Db::name('order')->where('id',$order_id)->update(['status' => 2]);

       return $result;
    }


    /**
     *
     * 获取用户邀请好友任务
     * */

    public function getUserInviteTask($parent_id)
    {
       $whereOne = [
            ['task_type','=',1],
            ['user_id','=',$parent_id]
       ];

       $whereTwo = [
           ['task_type','=',6],
           ['user_id','=',$parent_id]
       ];

       $tasks =  Db::name('user_task')
                    ->field('id,task_type,join_num,finish_join_num,give_integral,give_coupon,order_id')
                    ->where([$whereOne,$whereTwo])
                    ->withAttr('give_coupon',function ($value){
                        if (empty($value)){
                            return [];
                        }
                        return  json_decode($value,true);
                    })->whereBetweenTimeField('start_time','end_time')
                    ->select();


       return $tasks;
    }

    /**
     * 更改用户任务状态
     * */
    private function changeUserTask($user_task_id,$data)
    {
        $result = Db::name('user_task')->where('id',$user_task_id)->update($data);

        return $result;
    }

    /**
     *
     * 发放积分
     * */
    private function changeUserIntegral($user_id,$give_integral)
    {
        Db::name('user')->where('user_id',$user_id)->inc('integral',$give_integral)->update();
    }


    /**
     * 获取会员层级
     * */
    private function getUserLevelPath($parent_id)
    {
        $parent_path = Db::name('user')->where('id',$parent_id)->value('parent_path');

        $level_path = $parent_path . '-' . $parent_id;


        return $level_path;
    }

    /**
     *
     * 生成层级关系
     * */

    private function generateLevelData($level_path,$user_id)
    {
        Db::name('user')->where(['user_id' => $user_id])->update(['parent_path' => $level_path]);
        $levels = explode('-',$level_path);

        array_shift($levels);
        array_splice($levels,-1,3);

        $levelArr = [];
        $level_num = 0;

        foreach ($levels as $k => $v){
            $level_num++;
            $levelArr[$k]['parent_user_id'] = $v;
            $levelArr[$k]['user_id'] = $user_id;
            $levelArr[$k]['level'] = $level_num;
        }

        Db::name('user_level')->insertAll($levelArr);

    }






}
